<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/23
 * Time: 21:30
 */
namespace app\admin\model;

use think\Model;
use think\Image;

class Cases extends Model
{
    public function search($keyword)
    {
        // 搜索所有的数据,如果需要搜索其他字段需要自己添加
        $where = 1;
        $where .= " and (case_title like '%$keyword%')";
        /** 翻页 **********/
        //1 . 算出总的记录数
        $count = $this->where($where)->count();
        // 2. 生成翻页类的对象
        $page = input('page')?:1;
        $page = new \Component\Page($count,10,$page);
        $page->config['header'] = '个案例';
        // 3. 生成翻页的字符串：上一页、下一页
        $pageStr = $page->fpage();
        // 4. 取出当前页的数据
        $data = db('cases')->where($where)->limit( $page->limit)->order("id desc")->select();
        return array(
            'page' => $pageStr,
            'cases_data' => $data,
        );
    }

    /**
     * 上传图片
     */
    public function upload($case)
    {
        $data = [];
        // 如果上传了图片，并且图片是在临时目录中的（说明是新上传的）
        if($case['original_img'] && strpos($case['original_img'], 'tmp') !== FALSE)
        {
            if(isset($case['id']))
            {
                // 修改就删除原图
                if(isset($case['old_img']))
                {
                    foreach ($case['old_img'] as $v)
                    {
                        $v = ROOT_PATH.'public'.$v;
                        if(is_file($v))
                        {
                            unlink($v);
                        }
                    }
                }
            }
            //优化代码
            $rootPath = ROOT_PATH.'public/';
            // 构造图片存放目录的路径
            $date = date('Y-m',time());
            //目录结构宽高/年月组成
            $dir =$rootPath."/assets/upload/cases/$date/original";
            $thumb100 =$rootPath."/assets/upload/cases/$date/thumb/100x";
            $thumb300 =$rootPath."/assets/upload/cases/$date/thumb/300x";
            if(!is_dir($dir))
            {
                mkdir($dir, 0777,true);
            }
            if(!is_dir($thumb100))
            {
                mkdir($thumb100, 0777,true);
            }
            if(!is_dir($thumb300))
            {
                mkdir($thumb300, 0777,true);
            }
            $adName = time().'.'.substr(strrchr($case['original_img'], '.'), 1);
            $imgName = $dir.'/'. $adName; //原图
            $thumb1_logo = $thumb100.'/'.$adName;  //100
            $thumb2_logo = $thumb300.'/'. $adName;  //300
            copy($rootPath.$case['original_img'],$imgName);
            $image = Image::open($imgName);
            $image->thumb(300, 175,2)->save($thumb2_logo);
            $image->thumb(100, 58,2)->save($thumb1_logo);
            $data['original_img'] = substr($imgName,strlen($rootPath));
            $data['thumb2_img'] = substr($thumb2_logo,strlen($rootPath));
            $data['thumb1_img'] = substr($thumb1_logo,strlen($rootPath));
        }
        return $data;
    }
}